package com.shyroke.daydayzhuansvc.service.impl;

import com.shyroke.daydayzhuanapi.constant.RedisKeyPrefix;
import com.shyroke.daydayzhuanapi.dto.TypeDto;
import com.shyroke.daydayzhuanapi.entity.TypeEntity;
import com.shyroke.daydayzhuanapi.mapper.TypeMapper;
import com.shyroke.daydayzhuandao.respository.TypeRepository;
import com.shyroke.daydayzhuansvc.service.ITypeService;
import com.shyroke.daydayzhuansvc.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 类名 ：
 * 用法 ：
 * 创建人 ： shyroke
 * 时间：2019/1/29 9:27
 */
@Service
public class TypeService implements ITypeService {

    @Autowired
    private TypeRepository typeRepository;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TypeMapper typeMapper;

    @Override
    public List<TypeDto> getTypeList() {

        List<TypeDto> typeList = null;

        //判断缓存中是否存在，如果存在则返回，否则返回null
        typeList = RedisUtils.readList(RedisKeyPrefix.TYPELIST);

        if(typeList == null){
            typeList = new ArrayList<>();
            Iterator<TypeEntity> iterator = typeRepository.findAll().iterator();
            while (iterator.hasNext()) {
                TypeEntity entity = iterator.next();
                typeList.add(typeMapper.entityToDto(entity));
            }

            redisTemplate.opsForValue().set(RedisKeyPrefix.TYPELIST,typeList);
        }

        return typeList;
    }

    public List<TypeDto> findAll() {
        Iterator<TypeEntity> iterator = typeRepository.findAll().iterator();
        List<TypeDto> typeList = new ArrayList<>();
        while (iterator.hasNext()) {
            TypeEntity entity = iterator.next();
            typeList.add(typeMapper.entityToDto(entity));
        }
        return typeList;
    }


    public TypeDto findByUrl(String requestURI) {
        List<TypeDto> typeList = this.getTypeList();
        for (TypeDto type : typeList) {
            String href = type.getHref();
            if(href.equals(requestURI)){
                return type;
            }
        }
        return null;
    }


}
